<?php
class XA_DataType_Tree {


	public static function getDepthList($tree, $depth = 0) {
		$return = array();
		if (is_array($tree)) {
			foreach ($tree as $item) {
				$return[] = array_merge($item['item'], array('depth' => $depth));
				if (isset($item['children'])) {
					$return = array_merge($return, self::getDepthList($item['children'], $depth + 1));
				}
			}
		}
		return $return;
	}



	public static function get($rows, $index_name, $parent_name = null) {

		if (!$parent_name) {
			$parent_name = 'parent_id';
		}
		
		$index = array();
		foreach ($rows as $key => $item) {
			$index[$item[$index_name]] = array('item' => $item);
		}
		
		$tree = array();
		foreach ($index as $id => $item) {
			if ($item['item'][$parent_name] && isset($index[$item['item'][$parent_name]])) {
				$index[$item['item'][$parent_name]]['children'][] = &$index[$id];
			} else {
				$tree[] = &$index[$id];
			}
		}

		return $tree;
	}
}
?>